package com.example.demo_text;

import java.io.IOException;
import java.sql.SQLException;

import user.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user;
        try {
            user = UserDAO.login(username, password);
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }

        if (user != null) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);

            // 判断用户类型进行跳转
            if ("admin".equalsIgnoreCase(user.getUserType())) {
                response.sendRedirect("AdmitHome.jsp"); // 管理员跳转
            } else {
                response.sendRedirect("home.jsp");      // 普通用户跳转
            }
        } else {
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}
